"""
Cross-platform hardware fingerprint generation.
Generates a 32-character hexadecimal hardware fingerprint without admin privileges.
Compatible with Windows and Linux.
"""
import hashlib
import platform
import subprocess
import uuid


def _read_file(path: str) -> str:
    """Read file content safely."""
    try:
        with open(path, "r", encoding="ascii") as f:
            return f.read().strip()
    except Exception:
        return ""


def _wmic(query: str) -> str:
    """Run wmic command and return first non-empty result."""
    try:
        out = subprocess.check_output(
            query, shell=True, stderr=subprocess.DEVNULL
        ).decode("utf-8", errors="ignore")
        for line in out.splitlines():
            line = line.strip()
            if line and line != query.split()[-1]:  # Skip header line
                return line
    except Exception:
        pass
    return ""


def get_cpu_short() -> str:
    """Get CPU brand and clock speed (non-privileged)."""
    system = platform.system()
    if system == "Windows":
        brand = _wmic("wmic cpu get name /value").split("=", 1)[-1].strip()
        clock = _wmic("wmic cpu get maxclockspeed /value").split("=", 1)[-1].strip()
        return f"{brand}@{clock}MHz"
    else:  # Linux
        info = _read_file("/proc/cpuinfo")
        for line in info.splitlines():
            if line.startswith("model name"):
                return line.split(":", 1)[1].strip()
        return "UnknownCPU"


def get_board_uuid() -> str:
    """Get motherboard UUID (accessible by regular users)."""
    system = platform.system()
    if system == "Windows":
        return _wmic("wmic csproduct get uuid /value").split("=", 1)[-1].strip()
    else:  # Linux
        return _read_file("/sys/class/dmi/id/product_uuid")


def get_mac() -> str:
    """Get MAC address of the first real network interface."""
    node = uuid.getnode()
    if (node >> 40) & 0xFF == 0xFF:  # If random value is returned
        return "000000000000"
    return uuid.UUID(int=node).hex[-12:]


def genfingerprint() -> str:
    """Generate a 32-character hardware fingerprint."""
    cpu = get_cpu_short()
    uuid_board = get_board_uuid()
    mac = get_mac()
    raw = "|".join([cpu, uuid_board, mac]).encode("utf-8")
    return hashlib.sha256(raw).hexdigest()[:32]  # 32 characters


# Demo usage
if __name__ == "__main__":
    print("Hardware fingerprint:", genfingerprint())
